<template>
<div class="depart-list content bg-white full-height page-content padding-t-20 padding-b-20">
<!--  <div class="form-inline">-->
    <!--<q-btn class="margin-r-10" outline color="primary" label="下载模板" type="a" :href="templateUrl" download />-->
    <!--<q-btn class="margin-r-10" outline color="primary" label="批量导入" >-->
      <!--<input type="file" @change="importFile($event)" multiple class="q-uploader__input overflow-hidden absolute-full"-->
             <!--accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">-->
    <!--</q-btn>-->
<!--    <q-btn @click="openAddOrEditDialog('add')" outline color="primary" label="添加部门" />-->
<!--  </div>-->
  <q-table
    :data="tableData" :columns="columns"
    row-key="name" class="scroll myTable-line depart-list-table"
    :loading="tableLoading" table-style="max-height: 100%"
    hide-bottom :pagination="{rowsPerPage: 0}"
    no-data-label="暂无数据">
    <template v-slot:body="props">
      <transition name="fade">
        <q-tr :props="props" v-show="props.row.show">
          <q-td key="index" :props="props" :style="{'padding-left': props.row.id === 0 ? '16px' : (props.row.level + 1)*20+16+'px', 'width': '300px'}">
            <q-btn :class="{'invisible': props.row.childrenCount===0}"
                   dense round flat size="sm"
                   :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'"
                   @click="toggleChildren(props.row)" />
            <span class="ellipsis inline-block" :style="{width:250-props.row.level*20-16+'px'}">
              {{ props.row.index }}
              <q-tooltip v-if="props.row.label.length>21">{{ props.row.label }}</q-tooltip>
            </span>
          </q-td>
          <q-td key="label" :props="props">{{ props.row.label }}</q-td>
          <q-td key="ownerName" :props="props">{{ props.row.ownerName }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime | toTime }}</q-td>
<!--          <q-td key="typeName" :props="props">{{ props.row.typeName }}</q-td>-->
<!--          <q-td key="departAttr" :props="props">{{ props.row.departAttr }}</q-td>-->
<!--          <q-td key="isTeam" :props="props">{{ props.row.teamFlag===1?'是':'否' }}</q-td>-->
<!--          <q-td key="remark" :props="props" style="width: 202px">-->
<!--            <span class="ellipsis inline-block" :style="{width:'170px'}">-->
<!--              {{ props.row.remark !== '' ? props.row.remark : '&#45;&#45;' }}-->
<!--              <q-tooltip v-if="props.row.remark.length>12">{{ props.row.remark !== '' ? props.row.remark : '&#45;&#45;' }}</q-tooltip>-->
<!--            </span>-->
<!--          </q-td>-->
          <q-td key="operate" :props="props" style="width: 100px">
            <table-btn btnType="other" icon="icontubiao-50" tooltip="添加子项" @click="addChild(props.row)" :class="{'invisible': props.row.teamFlag===1}"/>
            <table-btn btnType="edit" :disable="!props.row.id" @click="openAddOrEditDialog('edit', props.row)"/>
            <table-btn btnType="delete" :disable="!!props.row.locationNum || !props.row.id" @click="delDialog(props.row)" :tips="`确定要删除${props.row.label}吗？`"/>
          </q-td>
        </q-tr>
      </transition>
    </template>
  </q-table>
  <!--  添加编辑弹框-->
  <add-edit-dialog ref="addEditDialog" :org-list="departAttrList" @submit="submit"></add-edit-dialog>
</div>
</template>

<script>
import { getDepartTenant, addDepart, addDepartChild, editDepart, delDepart } from 'src/boot/factory/depart'
import { getDict } from 'src/boot/common/dict'
import AddEditDialog from './components/add-edit-depart-dialog'
import refreshMixin from '../../assets/js/refresh-mixin'
export default {
  name: 'depart-list',
  mixins: [refreshMixin],
  data () {
    return {
      departAttrList: [], // 组织层级数据
      // 筛选
      templateUrl: '/v1/depart/template', // 企业信息模板地址
      // table
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 所有标题
        { name: 'index', align: 'left', label: '序号', field: 'index', check: true },
        { name: 'label', align: 'left', label: '部门名称', field: 'label', check: true },
        { name: 'ownerName', align: 'left', label: '创建人', field: 'ownerName', check: true },
        { name: 'createTime', align: 'left', label: '创建时间', field: 'createTime', check: true },
        // { name: 'typeName', align: 'left', label: '部门属性', field: 'typeName', check: true },
        // { name: 'isTeam', align: 'left', label: '是否班组', field: 'isTeam', check: true },
        // { name: 'remark', align: 'left', label: '备注', field: 'remark', check: true },
        { name: 'operate', align: 'center', label: '操作', field: 'operate', check: true }
      ]
    }
  },
  created () {
    this.getList()
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.tableData = []
      this.getList()
    },
    // 初始化数据
    getInfo () {
      // 获取组织层级
      getDict('deptattribute').then(res => {
        this.departAttrList = res.data
      })
      this.getList()
    },
    // 获取表结构
    getList () {
      this.tableLoading = true
      getDepartTenant().then(res => {
        this.tableData = this.initInfo(res.data)
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 给数据添加show、expand、isFirst、isLast、 index属性
    initInfo (data) {
      let info
      if (this.tableData.length === 0) {
        info = data.map((item, index) => {
          const isLast = index === data.length - 1 ||
            (index !== 0 && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
            (index !== 0 && data[index - 1].id + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          // const isLast = index === data.length - 1 || item.level !== data[index + 1].level
          return {
            ...item,
            show: true,
            expand: true,
            isFirst: index === 0 || item.parentId + '' === data[index - 1].id + '',
            isLast: isLast,
            // index: index,
            parentId: item.parentId,
            id: item.id
          }
        })
      } else {
        info = data.map((item, index) => {
          let tableItem = this.tableData.find(f => {
            return Number(f.id) === Number(item.id)
          })
          const isLast = index === data.length - 1 ||
            (index !== 0 && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
            (index !== 0 && data[index - 1].id + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          // const isLast = index === data.length - 1 || item.level !== data[index + 1].level
          let parent = this.tableData.find(child => child.id + '' === item.parentId + '')
          return {
            ...item,
            show: tableItem ? tableItem.show : parent ? parent.expand : item.level === 0,
            expand: tableItem ? tableItem.expand : false,
            isFirst: index === 0 || item.parentId + '' === data[index - 1].id + '',
            isLast: isLast,
            // index: index,
            parentId: item.parentId,
            id: item.id
          }
        })
      }
      console.log(info)
      return info
    },
    // 显示隐藏子集
    toggleChildren (item) {
      item.expand = !item.expand
      let children
      if (item.expand) {
        children = this.findOneChild(item.id)
      } else {
        children = this.findChild(item.id)
      }
      const ids = children.map(item => {
        return item.id
      })
      this.tableData.forEach(i => {
        if (ids.includes(i.id)) {
          i.show = item.expand
          // i.expand = item.expand
        }
      })
    },
    // 找到下面一级的子集id
    findOneChild (id) {
      const data = JSON.parse(JSON.stringify(this.tableData))
      let children = data.filter((item) => {
        return item.parentId === id
      })
      let child = this.findExpandChild(children)
      children = children.concat(child)
      return children
    },
    // 找到展开的子级
    findExpandChild (arr) {
      let result = []
      arr.forEach(item => {
        if (item.expand) {
          let child = this.findOneChild(item.id)
          result = result.concat(child)
        }
      })
      return result
    },
    // 找到下面的所有子集id
    findChild (id) {
      const data = JSON.parse(JSON.stringify(this.tableData))
      let child = data.filter((item) => {
        return item.parentId === id
      })
      child.forEach(item => {
        if (item.childrenCount > 0) {
          const newArr = this.findChild(item.id)
          child = child.concat(newArr)
        }
      })
      return child
    },
    // 打开添加编辑弹框
    openAddOrEditDialog (state = 'add', item) {
      if (state === 'add' && this.treeAct === null) {
        this.$message.warning('请选择先组织')
        return false
      }
      this.$refs.addEditDialog.showDialog(state, item)
    },
    addChild (item) {
      const info = {
        ...item,
        label: null,
        parentName: item.label,
        parentId: item.id,
        organizeClassName: null,
        remark: ''
      }
      this.$refs.addEditDialog.showDialog('child', info)
    },
    // 提交添加编辑弹框
    submit (state, info) {
      switch (state) {
        case 'add':
          addDepart(info).then(() => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`添加${info.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
        case 'child':
          addDepartChild(info).then(() => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`添加${info.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
        case 'edit':
          editDepart(info).then(() => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`编辑${info.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
      }
    },
    // 删除弹框
    delDialog (item) {
      delDepart(item.id).then(() => {
        this.$message.success(`删除${item.label}成功`)
        this.getList()
      })
    },
    // 批量导入上传文件
    importFile (event) {
      // this.$q.loading.show()
      // importFile(event.target.files).then((res) => {
      //   console.log(res)
      //   this.$q.loading.hide()
      //   this.$q.dialog({
      //     title: '提示',
      //     message: res.message
      //   })
      // })
    }
  },
  components: {
    AddEditDialog
  }
}
</script>

<style scoped lang="stylus">
.depart-list{
  .depart-list-table span{
    vertical-align middle
  }
}
</style>
